package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.constants.message.NewsAutoScanConstants;
import com.heima.model.common.constants.message.NewsUpOrDownConstants;
import com.heima.model.common.constants.message.PublishArticleConstants;
import com.heima.model.common.constants.wemedia.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews>implements WmNewsService {

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Value("${file.oss.web-site}")
    String webSite;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {

        if (dto==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        // 1. 如果有文章标题，按照文章标题模糊查询
        LambdaQueryWrapper<WmNews> wrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNoneBlank(dto.getKeyword())) {
            wrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        // 2. 如果有频道信息，按照频道ID查询
        if (dto.getChannelId()!=null) {
            wrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        // 3. 如果有文章状态，按照状态信息进行查询
        if (dto.getStatus()!=null) {
            wrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        // 4. 如果开始时间，结束时间不为空按照时间区间查询
        if (dto.getBeginPubDate()!=null) {
            wrapper.ge(WmNews::getPublishTime,dto.getBeginPubDate());
        }
        if (dto.getEndPubDate()!=null) {
            wrapper.le(WmNews::getPublishTime,dto.getEndPubDate());
        }
        // 5. 按照登录用户ID去查询
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        wrapper.eq(WmNews::getUserId,user.getId());
        // 6. 按照创建时间降序
        wrapper.orderByDesc(WmNews::getCreatedTime);
        // 7. 分页查询，返回结果设置host  地址 为图片访问前缀
        Page<WmNews> pageResult = new Page<>(dto.getPage(),dto.getSize());
        IPage<WmNews> page = page(pageResult, wrapper);
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), page.getTotal(), page.getRecords());
        responseResult.setHost(webSite);
        return responseResult;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult submitNews(WmNewsDTO dto) {
        //  1. 参数校验
        if (StringUtils.isBlank(dto.getContent())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //  2. 保存或修改文章
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        //* 该功能为保存、修改（是否有id）、保存草稿的共用方法
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        String image = imageListToStr(dto.getImages());
        wmNews.setImages(image);
        saveWmNews(wmNews);
        if (WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(dto.getStatus())) {
            return ResponseResult.okResult();
        }
        //  3. 关联文章和素材关系表
        //解析素材中的图片url
        List<String> materialUrlList = parseContentImages(dto.getContent());
        //* 关联**内容**中的图片与素材的关系
        if (CollectionUtils.isNotEmpty(materialUrlList)) {
            saveRelativeInfoForContent(materialUrlList,wmNews);
        }
        //* 关联**封面**中的图片与素材的关系
        saveRelativeInfoForCover(materialUrlList,wmNews,dto);
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());
        log.info("成功发送 文章自动审核消息 待审核文章id: {}",wmNews.getId());
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult findWmNewsById(Integer id) {
        if (id==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(id);
        if (wmNews==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        if (dto==null || dto.getId()==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Short enable = dto.getEnable();
        if (enable==null || (!WemediaConstants.WM_NEWS_UP.equals(enable)&&!WemediaConstants.WM_NEWS_DOWN.equals(enable))) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"上下架状态错误");
        }
        WmNews wmNews = getById(dto.getId());
        if (wmNews==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"该文章不存在");
        }
        if (!WemediaConstants.WM_NEWS_PUBLISH_STATUS.equals(wmNews.getStatus())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"当前文章不是发布状态,不能下架");
        }
        update(Wrappers.<WmNews>lambdaUpdate()
                .eq(WmNews::getId,dto.getId()).set(WmNews::getEnable,dto.getEnable()));
        if(wmNews.getArticleId()!=null){
            if (WemediaConstants.WM_NEWS_UP.equals(dto.getEnable())) {
                // 上架
                rabbitTemplate.convertAndSend(
                        NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY,
                        wmNews.getArticleId()
                );
                log.info(" 文章上架消息  成功发送  文章id:{}",wmNews.getArticleId());
            }else {
                // 下架
                rabbitTemplate.convertAndSend(
                        NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,
                        wmNews.getArticleId()
                );
                log.info(" 文章下架消息  成功发送  文章id:{}",wmNews.getArticleId());
            }
        }
        return ResponseResult.okResult();

    }

    @Override
    public ResponseResult delNews(Integer id) {
        if (id==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(id);
        if (wmNews==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"该文章不存在");
        }
        if (!WemediaConstants.WM_NEWS_PUBLISH_STATUS.equals(wmNews.getStatus())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"当前文章不是发布状态,不能下架");
        }
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
        removeById(wmNews.getId());
        return ResponseResult.okResult();
    }

    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Override
    public ResponseResult findAuthList(NewsAuthDTO dto) {
        dto.checkParam();
        Integer page = dto.getPage();
        dto.setPage((dto.getPage()-1)*dto.getSize());
        if (StringUtils.isNoneBlank(dto.getTitle())) {
            dto.setTitle("%"+dto.getTitle()+"%");
        }
        List<WmNewsVO> wmNewsVOList = wmNewsMapper.findListAndPage(dto);
        Long count = wmNewsMapper.findListCount(dto);
        PageResponseResult result = new PageResponseResult(page,dto.getSize(),count,wmNewsVOList);
        result.setHost(webSite);
        return result;
    }

    @Autowired
    private WmUserMapper wmUserMapper;

    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        if (id==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(id);
        if (wmNews==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        WmUser wmUser = null;
        if (wmNews.getUserId()!=null) {
            wmUser=wmUserMapper.selectById(wmNews.getUserId());
        }
        WmNewsVO wmNewsVO = new WmNewsVO();
        BeanUtils.copyProperties(wmNews,wmNewsVO);
        if (wmUser!=null) {
            wmNewsVO.setAuthorName(wmUser.getName());
        }
        ResponseResult result = ResponseResult.okResult(wmNewsVO);
        result.setHost(webSite);
        return result;
    }

    @Override
    public ResponseResult updateStatus(Short wmNewsAuthPass, NewsAuthDTO dto) {
        if (dto==null || dto.getId()==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(dto.getId());
        if (wmNews==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章不存在");
        }
        if (wmNewsAuthPass.equals(WemediaConstants.WM_NEWS_PUBLISH_STATUS)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章已发布");
        }
        wmNews.setStatus(wmNewsAuthPass);
        if (StringUtils.isNoneBlank(dto.getMsg())) {
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);
        long publishTime = wmNews.getPublishTime().getTime();
        long nowTime = System.currentTimeMillis();
        long time = publishTime - nowTime;
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE,
                PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY,
                wmNews.getId(),
                message -> {
                    message.getMessageProperties().setHeader("x-delay",time <= 0 ? 0 : time);
                    return message;
                }
        );
        log.info("成功发送  发布文章消息   待发布的文章id: {}",wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private void saveRelativeInfoForCover(List<String> materialUrlList, WmNews wmNews, WmNewsDTO dto) {
        List<String> images = dto.getImages();
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            int size = materialUrlList.size();
            if (size>0&&size<=2) {
                images = materialUrlList.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            }else if (size>2){
                images = materialUrlList.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            }else {
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            if (CollectionUtils.isNotEmpty(images)) {
                wmNews.setImages(imageListToStr(images));
            }
            updateById(wmNews);
        }
        // 如果不为空 保存关联关系
        if(!CollectionUtils.isEmpty(images)){
            images = images.stream().map(url->url.replaceAll(webSite,"")).collect(Collectors.toList());
            saveRelativeInfo(images,wmNews,WemediaConstants.WM_IMAGE_REFERENCE);
        }


    }

    //保存文章内容图片和素材的关联关系
    private void saveRelativeInfoForContent(List<String> materialUrlList, WmNews wmNews) {
        saveRelativeInfo(materialUrlList,wmNews,WemediaConstants.WM_CONTENT_REFERENCE);
    }

    /**
     * 保存关联关系
     * @param materialUrlList
     * @param wmNews
     * @param type
     */
    private void saveRelativeInfo(List<String> materialUrlList, WmNews wmNews, Short type) {
        //根据url查询对应的id
        List<Integer> ids = wmMaterialMapper.selectRelationsIds(materialUrlList,WmThreadLocalUtils.getUser().getId());
        if (ids.size()<materialUrlList.size()|| CollectionUtils.isEmpty(ids)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"引用的素材不存在");
        }
        wmNewsMaterialMapper.saveRelations(ids,wmNews.getId(),type);
    }

    private List<String> parseContentImages(String content) {
        List<Map> maps = JSON.parseArray(content, Map.class);
        return maps.stream()
                .filter(m -> WemediaConstants.WM_NEWS_TYPE_IMAGE.equals(m.get("type")))
                .map(m -> (String) m.get("value"))
                .map(url-> url.replace(webSite,""))
                //去重
                .distinct()
                .collect(Collectors.toList());
    }

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    private void saveWmNews(WmNews wmNews) {
        wmNews.setCreatedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setPublishTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);//上架
        if (wmNews.getId()==null) {
            save(wmNews);
        }else {
            //* 如果有id修改文章，先删除所有素材关联关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            updateById(wmNews);
        }
    }

    private String imageListToStr(List<String> images) {
        return images.stream().map(url->
                url.replace(webSite,""))
                .collect(Collectors.joining(","));
    }
}
